<script setup lang="ts">
import {ref, reactive, onMounted, onBeforeMount} from "vue";
import {reqGetCode, reqRegister} from "@/api/user";
//封装用户信息
let userinfo = reactive({
  email: '',
  password: '',
  code: ''
})
//显示验证码倒计时
let codeText: any = ref("获取验证码")
//是否能再次发送验证码
const isSendCode = ref(false)
//定时器
let timer: any = null;
//发送验证码
const sendCode = async (cacheTime?: any) => {
  //判断邮箱是否填写
  if (!userinfo.email) {
    uni.showToast({
      title: "请先填写邮箱",
      icon: "none"
    })
    return
  }

  //倒计时
  let time = ref(60)

  console.log(cacheTime);

  if (cacheTime) {
    time.value = cacheTime
  }
  isSendCode.value = true
  codeText.value = time.value + "秒后获取"

  //发送验证码
  if (!cacheTime) {
    await reqGetCode(userinfo.email).then(res => {
      if (res.code == 200) {
        uni.showToast({
          title: "验证码发送成功，请注意查看邮箱",
          icon: "none"
        })
      } else {
        uni.showToast({
          title: res.msg,
          icon: "error"
        })
        isSendCode.value = false
        codeText.value = "获取验证码"
        timer.value = 60
        if (timer) {
          clearInterval(timer)
        }
      }
    })
  }

  timer = setInterval(() => {
    if (time.value > 0) {
      time.value--
      codeText.value = time.value + "秒后获取"
      uni.setStorageSync("sxg:codeText", time.value)
    } else {
      codeText.value = "获取验证码"
      isSendCode.value = false
      clearInterval(timer)
    }
  }, 1000)
}
//定义表单收集规则
const rules = {
  "username": [
    {
      type: 'string',
      required: true,
      message: '邮箱不能为空',
      trigger: ['blur']
    },
    {
      // 自定义验证函数，见上说明
      validator: (rule, value, callback) => {
        // 上面有说，返回true表示校验通过，返回false表示不通过
        // uni.$u.test.mobile()就是返回true或者false的
        return uni.$u.test.email(value);
      },
      message: '邮箱格式不正确',
      // 触发器可以同时用blur和change
      trigger: ['blur'],
    }
  ],
  "password": [
    {
      type: 'string',
      required: true,
      message: '密码不能为空',
      trigger: ['blur']
    }
  ],
  "code": [
    {
      type: 'string',
      required: true,
      message: '验证码不能为空',
      trigger: ['blur']
    },
  ]
}
//获取表单实例
let formUser = ref()
onMounted(() => {
  //刷新时检查是否有保存的验证码
  let storageCodeText = uni.getStorageSync("sxg:codeText");
  console.log(storageCodeText);
  if (storageCodeText) {
    sendCode(storageCodeText);
  }
//给表单设置收集规则
  formUser.value.setRules(rules)
})
//注册
const register = () => {
  formUser.value.validate().then(async () => {
    await reqRegister(userinfo).then(res => {
      if (res.code == 200) {
        uni.showToast({
          title: "注册成功",
          icon: "success"
        })
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/login/login'
          })
        }, 800)
      } else {

      }
    })
  })
}
//去登录页
const toLogin = () => {
  uni.reLaunch({
    url: '/pages/login/login'
  })
}
//离开时清除定时器
// onBeforeMount(() => {
//   clearInterval(timer)
//   uni.removeStorageSync("sxg:codeText")
// })
</script>

<template>
  <view class="bar"></view>

  <view class="container">
    <image style="margin-top: 20rpx" src="/static/images/login/Image@2x_1.png" mode="aspectFit"/>

    <h3 style="text-align: center;margin-top: 20rpx">注册账号</h3>

    <view class="from">

      <u--form
          labelPosition="left"
          :model="userinfo"
          ref="formUser"
      >
        <u-form-item
            prop="email"
            ref="item1"
        >
          <u--input
              class="from-item"
              placeholder="请输入邮箱"
              border="surround"
              shape="circle"
              prefixIcon="account"
              type="text"
              v-model="userinfo.email"
          ></u--input>
        </u-form-item>

        <u-form-item
            prop="password"
            ref="item1"
        >
          <u--input
              class="from-item"
              placeholder="请输入密码"
              :password="true"
              border="surround"
              prefixIcon="lock"
              shape="circle"
              type="password"
              v-model="userinfo.password"
          ></u--input>
        </u-form-item>

        <u-form-item
            prop="code"
            ref="item1"
        >
          <view class="code">
            <u--input
                class="from-item"
                placeholder="请输入验证码"
                border="surround"
                v-model="userinfo.code"
            ></u--input>
            <view>
              <up-button class="btn_code" color="#FF9E29" @click="sendCode()" :disabled="isSendCode"
                         size="mini">{{ codeText }}
              </up-button>
            </view>
          </view>
        </u-form-item>

        <u-form-item>
          <up-button class="from-item" color="#FF9E29" @click="register()" shape="circle">注册</up-button>
        </u-form-item>

      </u--form>

    </view>

    <view style="display: flex;justify-content: center;">
      已有账号&nbsp;&nbsp;
      <text style="color: #FF9E29" @click="toLogin()">去登录</text>
    </view>

  </view>
</template>

<style scoped lang="scss">
.container {
  width: 100vw;
  height: 100vh;
  background-color: rgba(238, 238, 238, 0.26);

  .title {
    background-color: #4cd964;
    width: 35vw;
  }

  image {
    width: 100%;
  }

  .from {
    margin: 40rpx auto;
    width: 80vw;

    .from-item {
      height: 80rpx;
    }

    .code {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;

      .code-time {
        color: #FF9E29;
        font-size: 28rpx;
        margin-left: 35rpx;
        border: 1px solid black;
        height: 80rpx;
      }

      .btn_code {
        width: 220rpx;
        margin-left: 35rpx;
        height: 80rpx;
      }

    }

  }


}
</style>
